import time
import os

# 中文数字转换为阿拉伯数字
def is_chinese_arabic(chinese_num):
    chinese_token = '零一二三四五六七八九十百千万亿'
    txt = str(chinese_num)
    for idx in range(len(chinese_token)):
        idx_str = chinese_token[idx]
        if txt.find(idx_str) >= 0:
            return True
    return False

# 中文数字转换为阿拉伯数字
def chinese_to_arabic(chinese_num):
    num_dict = {'零': 0, '一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9, '十': 10, '百': 100, '千': 1000, '万': 10000, '亿': 100000000}
    result = 0
    temp = 0
    for char in chinese_num:
        if char in num_dict:
            if char in {'十', '百', '千', '万', '亿'}:
                if temp == 0:
                    temp = num_dict[char]
                else:
                    temp = temp * num_dict[char]
                    result += temp
                    temp = 0
            else:
                temp = temp * 10 + num_dict[char]
    result += temp
    return result

# 去除前后空白字串
def trim(s):
    if(s==None or s == ''):
        return ''
    # 左侧空格
    while(s[:1] == ' ' or s[:1] == '\t' or s[:1] == '\n'):
        s = s[1:]
    # 右侧空格
    while(s[-1:] == ' ' or s[-1:] == '\t' or s[-1:] == '\n'):
        s = s[:-1]
    return s

# 取的目录下的档案数量
def file_count(directory):
    count = 0
    for file_name in os.listdir(directory):
        file_path = os.path.join(directory, file_name)
        if os.path.isfile(file_path):
            count += 1
    return count

# 检查档案名称
def check_filename(name):
    name = (str(name) or "").replace("?", "")
    name = name.replace("|", "")
    name = name.replace("\\", "")
    name = name.replace("/", "")
    name = name.replace(".", "")
    name = name.replace(":", "")
    name = name.replace(">", "")
    name = name.replace("<", "")
    name = name.replace('"', "")
    name = name.replace('*', "")
    return name

# 检查 author
def check_author(author):
    if type(author) == list:
        if len(author) > 0:
            author = author[0]
        else:
            author = ''
    author = trim(str(author).split(",", maxsplit=1)[0])
    author = trim(str(author).split("|", maxsplit=1)[0])
    author = check_filename(author)

# 检查目录，回传目录下的档案数量
def check_directory(topic, author, folder, root_path=""):
    author = check_filename(author)
    folder = check_filename(folder)
    if author == "":
        target_path = os.path.join(root_path, topic, folder)
    else:
        target_path = os.path.join(root_path, topic, author)
        if not os.path.exists(target_path):
            os.makedirs(target_path)
        target_path = os.path.join(root_path, topic, author, folder)
    #print(f'check_directory topic={topic}, author={author}, folder={folder}, path={target_path}')
    if not os.path.exists(target_path):
        os.makedirs(target_path)
    total = file_count(target_path)
    return total

# 取得档案的讯息
def get_info(author, folder, download_url, file_raw_name=""):
    info = {}
    author = check_filename(author)
    folder = check_filename(folder)
    info['author'] = author
    info['folder'] = folder
    full_name_query = download_url.split('/')[-1]
    full_name = full_name_query 
    query_list = full_name.split('?', maxsplit=1)
    query = ""
    if len(query_list) > 1:
        query = query_list[-1]
        full_name = query_list[0]
    file_ext = ""
    file_list = full_name.split('.')
    if len(file_list) > 1:
        file_ext = file_list[-1] or ""
        if file_ext == "":
            file_raw = full_name
        else:
            file_raw = full_name.replace(f'.{file_ext}', '')
    else:
        file_raw = full_name
    if file_raw_name != "":
        file_raw = check_filename(file_raw_name)
    root_url = download_url.replace(full_name_query, '')
    info['download_url'] = download_url
    info['file_raw'] = file_raw
    info['file_ext'] = file_ext
    info['root_url'] = root_url
    info['query'] = query
    info['page_no'] = 0
    return info

# 检查档案是否存在，回传保存的档案名称和网址
def check_file(topic, info, root_path=""):
    author = info['author'] or ''
    folder = info['folder'] or ''
    page_no = info['page_no'] or 0
    root_url = info['root_url'] or ''
    download_url = info['download_url'] or ''
    file_ext = info['file_ext'] or ""
    if topic == "comic" or topic == "comics":
        page_name = str(page_no+1).zfill(6)
    else:
        page_name = info['file_raw'] or ""
    ext_dot = ""
    if file_ext != "":
        ext_dot = "."
    if author == "":
        file_name = os.path.join(root_path, topic, folder, f'{page_name}{ext_dot}{file_ext}')
    else:
        file_name = os.path.join(root_path, topic, author, folder, f'{page_name}{ext_dot}{file_ext}')
    result = {
        "folder": folder,
        "file_name": file_name,
        "new_url": ""
    }
    #print(f'utils.check_file file_name={file_name}')
    if not os.path.exists(file_name):
        if topic == "comic" or topic == "comics":
            result["new_url"] = f'{root_url}{page_no+1}{ext_dot}{file_ext}'
        else:
            result["new_url"] = download_url
    #print(f'check_file folder={result["folder"]}, file_name={result["file_name"]}, new_url={result["new_url"]}')
    return result


#Main Run Thread
# if __name__=='__main__':
#     print("Utils :")
#     chinese_token = '零一二三四五六七八九十百千万亿'
#     txt = "122"
#     print(f'{txt}={is_chinese_arabic(txt)},{chinese_to_arabic(txt)}')
#     txt = "二十五"
#     print(f'{txt}={is_chinese_arabic(txt)},{chinese_to_arabic(txt)}')